package com.badibadi.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.badibadi.adapter.MyPolyAdapter;
import com.badibadi.fragment.MyPolyFragment;
import com.badibadi.infos.ImageAttribute;
import com.badibadi.infos.PhotoModel;
import com.badibadi.infos.Results;
import com.badibadi.logic.ImgFileListActivity;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.TabHostUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.OnTabChangeListener;

public class MyPoly1Activity extends BaseActivity {// my_poly_setting
	protected static final String TAG = "MyPoly1Activity";
	private TabHost mTabHost;
	private PopupWindow poWindows;
	private boolean PopVisible = false;
	View root;
	List<PhotoModel> mList;
	public String uid = "6";
	public String fid = "-1";
	public MyPolyFragment fragment0;
	// 版型 有三种 默认0 1参考 ， 2四个格子
	private String Version = "0";
	private FragmentManager manager;
	private ImageAttribute imageAttribute;
	private Results resultsss;
	/**
	 * 显示什么
	 */
	private int type = -1;// 0足迹，1梦想 2收藏 -1 全部
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {

			case 2:
				Utils.ExitPrgress(MyPoly1Activity.this);
				Utils.showMessage(MyPoly1Activity.this, getResources()
						.getString(R.string.l_net_error));
				break;
			case 3:
				Utils.ExitPrgress(MyPoly1Activity.this);
				try {
					Utils.showMessage(MyPoly1Activity.this, getResources()
							.getString(R.string.l_xb147));
				} catch (Exception e) {
				}

				break;

			case 4:
				Utils.ExitPrgress(MyPoly1Activity.this);
				Utils.showMessage(MyPoly1Activity.this, getResources()
						.getString(R.string.l_xa10));
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.activity_my_poly1);
		TextView title = (TextView) this.findViewById(R.id.title);
		title.setText(getResources().getString(R.string.l_xb106));

		uid = Utils.getUid(MyPoly1Activity.this);
		fid = getIntent().getStringExtra("fid");
		if (fid == null) {
			fid = "-1";
		}
		// 子界面复用他
		initId();
//		   
		init();
		Environment.getExternalStorageDirectory().toString();
		initFragment();
	}

	// 这个不能删掉，子类重写他
	public void initId() {

	}

	private void initFragment() {
		LoadingFragment(0, uid, fid);
	}

	/**
	 * 读取到fragment
	 * 
	 * @param num
	 */
	private void LoadingFragment(int num, String uid, String fid) {
		FragmentTransaction transaction = manager.beginTransaction();
		switch (num) {
		case 0:
			fragment0 = MyPolyFragment.getInstance();
			Bundle bun = new Bundle();
			bun.putString("uid", uid);
			bun.putString("fid", fid);
			bun.putInt("type", -1);
			fragment0.setArguments(bun);
			transaction.replace(R.id.my_poly1_layout, fragment0);
			break;
		case 1:
			fragment0 = MyPolyFragment.getInstance();
			Bundle bun1 = new Bundle();
			bun1.putString("uid", uid);
			bun1.putString("fid", fid);
			bun1.putInt("type", 0);
			fragment0.setArguments(bun1);
			transaction.replace(R.id.my_poly1_layout, fragment0);
			break;
		case 2:
			fragment0 = MyPolyFragment.getInstance();
			Bundle bun2 = new Bundle();
			bun2.putString("uid", uid);
			bun2.putString("fid", fid);
			bun2.putInt("type", 1);
			fragment0.setArguments(bun2);
			transaction.replace(R.id.my_poly1_layout, fragment0);
			break;
		case 3:
			fragment0 = MyPolyFragment.getInstance();
			Bundle bun3 = new Bundle();
			bun3.putString("uid", uid);
			bun3.putString("fid", fid);
			bun3.putInt("type", 2);
			fragment0.setArguments(bun3);
			transaction.replace(R.id.my_poly1_layout, fragment0);
			break;
		}
		transaction.commit();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 5 && resultCode == 5) {
			imageAttribute = (ImageAttribute) data
					.getSerializableExtra("img_info");
			imgInformationSave();
		}
	}

	private void imgInformationSave() {
		Utils.showPrgress(MyPoly1Activity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", "1");
				map.put("cid", "0");
				map.put("activity_id", 0);
				map.put("record_id", 0);
				map.put("record_article_id", 0);
				map.put("zhan_num", 0);
				try {
					map.put("img", fengzhuang_upimginfo());
				} catch (JSONException e) {
					   
				}
//				   ("上传图片发送参数是:" + map.toString());
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "photo/imgInformationSave");
				if (content != null) {
					resultsss = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   ("保存图片返回的结果是:" + content + " "
//							+ resultsss.getRetmsg());
					if (resultsss != null && !resultsss.equals("null")
							&& resultsss.isRet()) {
						mHandler.sendEmptyMessage(3);
					} else {
						mHandler.sendEmptyMessage(4);
					}
				} else {
					mHandler.sendEmptyMessage(2);
				}
			}
		});
	}

	private void init() {
		manager = getSupportFragmentManager();
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						MyPoly1Activity.this.finish();
					}
				});

		mTabHost = (TabHost) findViewById(R.id.my_poly_tabhost);
		mTabHost.setup();
		mTabHost.addTab(mTabHost
				.newTabSpec("my_poly1 one")
				.setIndicator(getResources().getString(R.string.All),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab1));
		mTabHost.addTab(mTabHost
				.newTabSpec("my_poly1 two")
				.setIndicator(getResources().getString(R.string.Footprint),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab2));
		mTabHost.addTab(mTabHost
				.newTabSpec("my_poly1 one")
				.setIndicator(getResources().getString(R.string.Dream),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab3));
		mTabHost.addTab(mTabHost
				.newTabSpec("my_poly1 two")
				.setIndicator(getResources().getString(R.string.Collection),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab4));
		TabHostUtils.SetTabHost(MyPoly1Activity.this, mTabHost);

		mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				switch (mTabHost.getCurrentTab()) {
				case 0:
					LoadingFragment(0, uid, fid);
					break;
				case 1:
					LoadingFragment(1, uid, fid);
					break;
				case 2:
					LoadingFragment(2, uid, fid);
					break;
				case 3:
					LoadingFragment(3, uid, fid);
					break;
				}
			}
		});
	}

	private JSONObject fengzhuang_upimginfo() throws JSONException {
		JSONObject object = new JSONObject();
		String s = "";
		if (imageAttribute.getService_img_address() != null
				&& !imageAttribute.getService_img_address().isEmpty()) {
			for (int i = 0; i < imageAttribute.getService_img_address().size(); i++) {
				s += imageAttribute.getService_img_address().get(i).toString();
			}
			//    ("______上传的图片地址是:" + s);
			object.put("path", s);
		}
		object.put("photoId", imageAttribute.getXiangceid());
		object.put("uid", Utils.getUid(MyPoly1Activity.this));
		object.put("title", getResources().getString(R.string.l_xb149));
		object.put("info", imageAttribute.getInfo());
		object.put("address", imageAttribute.getAbsolute_address());
		object.put("map_x", imageAttribute.getAddress_weidu());
		object.put("map_y", imageAttribute.getAddress_jingdu());
		object.put("participator", imageAttribute.getCanyu_persons());
		String t = "";
		if (imageAttribute.getBiaoqian_map() != null
				&& !imageAttribute.getBiaoqian_map().isEmpty()) {
			//    ("数" + imageAttribute.getBiaoqian_num());
			for (int j = 0; j < imageAttribute.getBiaoqian_num(); j++) {
				if (imageAttribute.getBiaoqian_map().get(j) != null) {
					t += imageAttribute.getBiaoqian_map().get(j) + ",";
				}
			}
			object.put("typeid", quchu_zuihou(t));
		}
		object.put("attachment", imageAttribute.getLaiyuan());
		object.put("is_show", imageAttribute.getIs_displaydongtai());
		return object;
	}

	private String quchu_zuihou(String s) {
		return s.substring(0, s.length() - 1);
	}

	public void OnClick(View view) {
		if (view.getId() == R.id.my_poly_setting)
			settingPopWindows();

		root.findViewById(R.id.my_poly1_uppicture).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(MyPoly1Activity.this,
								ImgFileListActivity.class);
						intent.putExtra("panduan", "set");
						startActivityForResult(intent, 5);
						poWindows.dismiss();
					}
				});
		root.findViewById(R.id.VersionToChoose).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						LayoutInflater lif = LayoutInflater
								.from(MyPoly1Activity.this);// R.layout.my_poly1_popwindows_import_layout
						View root2 = lif.inflate(
								R.layout.my_poly_banxin_xuanze, null);

						float width = getScreenSize(SCREENW);

						int dp80_px = DisplayUtil.dip2px(MyPoly1Activity.this,
								80);
						int dp50_px = DisplayUtil.dip2px(MyPoly1Activity.this,
								50);
						int dp300_px = DisplayUtil.dip2px(MyPoly1Activity.this,
								200);
						final PopupWindow poWindows2 = new PopupWindow(root2,
								(int) width, dp300_px);
						poWindows2.setBackgroundDrawable(new BitmapDrawable());
						poWindows2.setFocusable(true);
						poWindows2.setTouchable(true);
						poWindows2.setWidth(LayoutParams.WRAP_CONTENT);
						poWindows2.setHeight(LayoutParams.WRAP_CONTENT);
						poWindows2.setOutsideTouchable(true);
						poWindows2.showAtLocation(
								findViewById(R.id.my_poly1_layout),
								Gravity.BOTTOM, 0, 0);
						PopVisible = true;
						root2.findViewById(R.id.banxin_0).setOnClickListener(
								new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										Version = "0";
										setVersion(Version);

										poWindows2.dismiss();
									}

								});
						root2.findViewById(R.id.banxin_1).setOnClickListener(
								new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										Version = "1";
										setVersion(Version);
										poWindows2.dismiss();
									}
								});
						root2.findViewById(R.id.banxin_2).setOnClickListener(
								new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										Version = "2";
										setVersion(Version);
										poWindows2.dismiss();
									}
								});

						root2.findViewById(R.id.cancel).setOnClickListener(
								new View.OnClickListener() {

									@Override
									public void onClick(View v) {

										poWindows2.dismiss();
									}
								});

						poWindows.dismiss();
					}
				});

	}

	/**
	 * 加载一个悬浮对话框 有上传图片
	 */
	private void settingPopWindows() {
		root = this.getLayoutInflater().inflate(
				R.layout.my_poly1_popwindows_import_layout, null);
		float width = getScreenSize(SCREENW);

		root.findViewById(R.id.my_poly1_popwin_close).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						poWindows.dismiss();
					}
				});
		root.findViewById(R.id.create_new_poly).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(MyPoly1Activity.this,
								CreateNewPoly1Activity.class);
						startActivity(intent);
						poWindows.dismiss();
					}
				});

		int dp80_px = DisplayUtil.dip2px(MyPoly1Activity.this, 80);
		int dp50_px = DisplayUtil.dip2px(MyPoly1Activity.this, 50);
		int dp300_px = DisplayUtil.dip2px(MyPoly1Activity.this, 300);
		poWindows = new PopupWindow(root, (int) width, dp300_px);
		poWindows.setBackgroundDrawable(new BitmapDrawable());
		poWindows.setWidth(LayoutParams.MATCH_PARENT);
		poWindows.setHeight(LayoutParams.WRAP_CONTENT);
		poWindows.setFocusable(true);
		poWindows.setTouchable(true);
		poWindows.setOutsideTouchable(true);
		poWindows.showAtLocation(findViewById(R.id.my_poly1_layout),
				Gravity.BOTTOM, 0, 0);
		PopVisible = true;

	}

	private void setVersion(final String version) {
		if (fragment0 != null)
			fragment0.setPolyAdapter(new MyPolyFragment.SetMyPolyAdapter() {

				@Override
				public void setPolyAdapter(MyPolyAdapter adapter,
						GridView mGridView, List<PhotoModel> list) {
					if (adapter != null) {
						MyPolyAdapter adapter2 = new MyPolyAdapter(
								MyPoly1Activity.this, list, version);
						adapter2.setVersion(version);
						mGridView.setAdapter(adapter2);
					}
				}
			});
	}
	@Override
		protected void onDestroy() {			
			super.onDestroy();
			ImageLoader.getInstance().clearDiscCache();
			ImageLoader.getInstance().clearMemoryCache();
		}

}
